<template>
  <header class="navbar">
    <div class="logo">易交易</div>
    <div class="nav-flex-group">
      <nav class="nav-links">
        <slot name="nav-links">
          <a href="/" class="nav-link">首页</a>
          <a href="/product" class="nav-link">发布商品</a>
          <a href="/seller/orders" class="nav-link">交易信息</a>
          <a href="/chat" class="nav-link">聊天信息</a>
          <a href="/announcements" class="nav-link">公告</a>
        </slot>
      </nav>
      <div class="user-area">
      <template v-if="isLoggedIn">
        <div class="user-info" @click="toggleDropdown">
          <img :src="getAvatarUrl(user.avatar)" alt="User Avatar" class="avatar">
          <span class="nickname">{{ user.username || '用户' }}</span>
          <div class="dropdown" v-show="showDropdown">
            <a :href="user.role === 1 ? '/admin/profile' : '/profile'" class="dropdown-item">个人资料</a>
            <a href="/browse-history" class="dropdown-item">浏览历史</a>
            <a href="/buyer/orders" class="dropdown-item">我的订单</a>
            <a href="/settings" class="dropdown-item">设置</a>
            <a href="/logout" class="dropdown-item" @click.prevent="handleLogout">退出登录</a>
          </div>
        </div>
      </template>
      <template v-else>
        <button class="auth-btn login-btn" @click="$router.push('/login')">登录</button>
        <button class="auth-btn register-btn" @click="$router.push('/register')">注册</button>
      </template>
    </div>
    <!-- 页面特定操作区域插槽 -->
    <slot name="actions"><!-- 页面特定操作区域 --></slot>
    </div> <!-- nav-flex-group 结束标签 -->
  </header>
</template>

<script setup lang="ts">
const API_BASE = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000';
const getAvatarUrl = (avatar: string) => {
  if (!avatar) return defaultAvatar;
  if (avatar.startsWith('http') || avatar.startsWith('data:')) return avatar;
  if (avatar.startsWith('/uploads/')) return API_BASE + avatar;
  return defaultAvatar;
};

import { ref, onMounted } from 'vue';
import axios from 'axios';
import moment from 'moment';

// 本地状态管理
const showDropdown = ref(false);
const defaultAvatar = '';
const isLoggedIn = ref(false);
const user = ref({ username: '', nickname: '', avatar: '', role: 0 });

// 检查本地存储的 token 和用户信息
onMounted(() => {
  const token = localStorage.getItem('token');
  const userStr = localStorage.getItem('user');
  console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Navbar] 检查用户登录状态: token=${!!token}, user=${!!userStr}`);
  if (token && userStr) {
    isLoggedIn.value = true;
    try {
      const parsedUser = JSON.parse(userStr);
      user.value = { ...parsedUser, role: parsedUser.role ?? 0 };
      console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Navbar] 用户已登录:`, user.value);
    } catch (err) {
      console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [Navbar] 解析用户信息失败:`, err);
      user.value = { username: '', nickname: '', avatar: '', role: 0 };
    }
  } else {
    isLoggedIn.value = false;
    user.value = { username: '', nickname: '', avatar: '', role: 0 };
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Navbar] 用户未登录`);
  }
});

// 切换下拉菜单显示状态
const toggleDropdown = () => {
  showDropdown.value = !showDropdown.value;
};

// 点击外部关闭下拉菜单
document.addEventListener('click', (e) => {
  const userArea = document.querySelector('.user-area');
  if (!userArea?.contains(e.target as HTMLElement)) {
    showDropdown.value = false;
  }
});

// 处理退出登录（与Profile.vue一致）
const handleLogout = async () => {
  showDropdown.value = false;
  const token = localStorage.getItem('token');
  try {
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Navbar] 请求登出`);
    const res = await axios.post('/api/auth/logout', {}, {
      headers: { ...(token ? { 'Authorization': `Bearer ${token}` } : {}) }
    });
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Navbar] 登出响应:`, res.data);
    if (res.status === 200 && res.data.message === '登出成功') {
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      isLoggedIn.value = false;
      user.value = { username: '', nickname: '', avatar: '', role: 0 };
      console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Navbar] 登出成功，已清除本地存储`);
      window.location.reload();
    } else {
      alert(res.data.message || '退出登录失败');
      console.warn(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [WARN] [Navbar] 登出失败:`, res.data);
    }
  } catch (err) {
    const e = err as any;
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [Navbar] 登出异常:`, e, e?.response?.data);
    alert((e.response && e.response.data && e.response.data.message) || '网络错误，退出登录失败');
  }
};
</script>

<style scoped>
/* 通用按钮基础样式 */
.auth-btn {
  font-size: 16px;
  padding: 0.5rem 1.5rem;
  border-radius: 999px;
  outline: none;
  cursor: pointer;
  margin-left: 0.5rem;
  transition: all 0.2s;
  font-weight: 500;
  border: none;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

/* 登录按钮样式 */
.login-btn {
  background-color: #fff;
  color: #333;
  border: 1px solid #e2e8f0;
}
.login-btn:hover {
  background-color: #f8fafc !important;
  color: #2563eb !important;
  border-color: #2563eb !important;
}

/* 注册按钮样式 */
.register-btn {
  background-color: #2563eb;
  color: #fff;
  border: 1px solid #2563eb;
  font-weight: 600;
  box-shadow: 0 2px 6px rgba(37, 99, 235, 0.2);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 0.25rem;
}
.navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  padding: 0.8rem 5vw;
  height: 70px;
  background-color: #ffffff;
  border-bottom: 1px solid rgba(0, 0, 0, 0.08);
  border-radius: 0 0 12px 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  z-index: 1000;
  transition: all 0.3s ease;
}

.nav-flex-group {
  display: flex;
  align-items: center;
  margin-left: auto;
  gap: 2vw;
}

/* 激活状态样式 */
.nav-links a.active {
  color: var(--primary-text);
  font-weight: 600;
  border-bottom: 2px solid var(--primary-dark);
}

.logo {
  font-size: 24px;
  font-weight: 600;
  font-stretch: semi-expanded;
  color: var(--primary-text);
  letter-spacing: 1px;
  font-variant: small-caps;
}
.nav-links {
  display: flex;
  justify-content: flex-end;
  margin-right: 2rem;
}

.nav-links a {
  margin: 0 0.5rem;
  text-decoration: none;
  color: #333333;
  font-weight: bold;
  padding: 0.75rem 1.5rem;
  border-radius: 999px !important;
  font-weight: 500;
  transition: all 0.25s ease;
  text-decoration: none;
  cursor: pointer;
  display: inline-block;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  margin-left: 0.5rem;
  position: relative;
}

.nav-links a:hover:after {
  width: 70%;
}

.nav-links a:hover {
  color: #2563eb;
  transform: translateY(-2px);
}

.nav-links a.active {
  color: #2563eb;
}

.nav-links a.active:after {
  width: 70%;
}

.user-area {
  display: flex;
  align-items: center;
  gap: 1.2rem;
}

.dropdown {
  position: absolute;
  top: 60px;
  right: 2vw;
  min-width: 200px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.05);
  padding: 0.5rem 0;
  z-index: 1000;
  transition: all 0.2s ease;
  transform-origin: top right;
  opacity: 1;
  visibility: visible;
  transform: scale(1);
}



.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #f1f5f9;
  cursor: pointer;
  transition: all 0.2s ease;
  margin-right: 0.5rem;
}

.avatar:hover {
  border-color: #e2e8f0;
  transform: scale(1.05);
}

.nickname {
  font-weight: 500;
  color: #333333;
  cursor: pointer;
  line-height: 32px;
}

.dropdown {
  position: absolute;
  top: 60px;
  right: 2vw;
  min-width: 200px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.05);
  padding: 0.5rem 0;
  z-index: 1000;
  transition: all 0.2s ease;
  transform-origin: top right;
}

.dropdown-item {
  display: block;
  padding: 0.75rem 1.25rem;
  color: #333333;
  text-decoration: none;
  transition: all 0.2s ease;
}

.dropdown-item:hover {
  background-color: #f8fafc;
  color: #2563eb;
}

.show-dropdown .dropdown {
  transform: scale(1);
  opacity: 1;
  visibility: visible;
}

@media (max-width: 768px) {
  .nav-links {
    display: none;
  }

  .navbar {
    padding: 0.8rem 3vw;
  }
}
</style>